package com.dingding.manager.modules.system.service.impl;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.dingding.manager.common.beans.sys.CityRefOrganization;
import com.dingding.manager.common.beans.sys.Organization;
import com.dingding.manager.common.dao.Db;
import com.dingding.manager.common.dao.Page;
import com.dingding.manager.common.exception.BussinessException;
import com.dingding.manager.common.exception.enums.BizExceptionEnum;
import com.dingding.manager.core.aop.log.LogRecord;
import com.dingding.manager.core.shiro.ShiroKit;
import com.dingding.manager.core.shiro.ShiroUser;
import com.dingding.manager.core.util.ToolUtil;
import com.dingding.manager.modules.system.dao.OrganizationDao;
import com.dingding.manager.modules.system.dto.organization.ReqOrganizationAddDTO;
import com.dingding.manager.modules.system.dto.organization.ReqOrganizationListDTO;
import com.dingding.manager.modules.system.dto.organization.ResOrganizationDTO;
import com.dingding.manager.modules.system.service.OrganizationService;

/**
 * 
 * @ClassName: OrganizationServiceImpl
 * @Description: 机构管理service实现类
 * @author SUNZHICHENG
 * @date 2016年12月4日 上午11:54:38
 * @version V2.6.2
 */
@Service("organizationService")
public class OrganizationServiceImpl implements OrganizationService {

	@Resource(name = "organizationDao")
	OrganizationDao organizationDao;

	/**
	 * @Description: 根据id查询机构信息
	 * @date 2016年12月4日 下午6:59:41
	 * @author SUNZHICHENG
	 * @since V2.6.2
	 */
	@Transactional(value = "txManager", readOnly = true)
	@Override
	public ResOrganizationDTO getOrganizationById(Integer id) {
		// 获取机构信息
		ResOrganizationDTO resOrganizationDTO = organizationDao.getOrganizationById(id);

		// 根据机构的父级id查询父级名称
		if (ToolUtil.isNotEmpty(resOrganizationDTO) && ToolUtil.isNotEmpty(resOrganizationDTO.getParentId())) {
			Organization organization = Db.findById(resOrganizationDTO.getParentId(), Organization.class);
			if (ToolUtil.isNotEmpty(organization)) {
				// 将父级名称添加到机构信息
				resOrganizationDTO.setOrganizationName(organization.getOrganizationName());
			}
		}
		return resOrganizationDTO;
	}

	/**
	 * @Description: 获取所有机构
	 * @date 2016年12月5日 下午3:19:22
	 * @author SUNZHICHENG
	 * @since V2.6.2
	 */
	@Override
	@Transactional(readOnly = true)
	public List<Organization> getOrganizationList() {
		return organizationDao.getOrganizationList();
	}

	/**
	 * @Description:删除机构信息
	 * @date 2016年12月5日 下午7:12:20
	 * @author SUNZHICHENG
	 * @since V2.6.2
	 */
	@LogRecord(moduleName="公司管理",option="删除")
	@Override
	@Transactional(readOnly = false)
	public boolean deleteOrganization(Integer id) {
		return organizationDao.deleteOrganization(id);
	}

	/**
	 * @Description: 启用/禁用
	 * @date 2016年12月5日 下午7:13:52
	 * @author SUNZHICHENG
	 * @since V2.6.2
	 */
	@LogRecord(moduleName="公司管理",option="启用/禁用")
	@Override
	@Transactional(readOnly = false)
	public boolean modifyOrganizationState(Integer id, Integer state) {
		return organizationDao.modifyOrganizationState(id, state);
	}

	/**
	 * @Description: 添加机构
	 * @date 2016年12月7日 下午9:55:18
	 * @author SUNZHICHENG
	 * @since V2.6.2
	 */
	@LogRecord(moduleName="公司管理",option="添加")
	@Override
	@Transactional(readOnly = false)
	public void addOrganization(ReqOrganizationAddDTO reqOrganizationAddDTO) {

		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		// 获取当前登录用户信息
		ShiroUser shiroUser = ShiroKit.getUser();
		Integer currentId = shiroUser.getId();

		if (ToolUtil.isNotEmpty(reqOrganizationAddDTO.getOrganizationName())) {
			// 获取是否存在此机构
			List<Organization> organizationByName = organizationDao
					.getOrganizationByName(reqOrganizationAddDTO.getOrganizationName());
			if (!organizationByName.isEmpty()) {
				throw new BussinessException(BizExceptionEnum.INFO_REPEAT);
			}
			// 添加机构信息
			Organization organization = new Organization();
			// 公司类型为0总公司，设置其父级id为0
			if (reqOrganizationAddDTO.getOrganizationType() == 0) {
				organization.setParentId(0);
				organization.setParentIds("0,");
			} else {
				organization.setParentId(reqOrganizationAddDTO.getParentId());
				organization.setParentIds(reqOrganizationAddDTO.getParentId() + ",");
			}

			organization.setCityId(reqOrganizationAddDTO.getCityId());
			organization.setCityName(reqOrganizationAddDTO.getCityName());
			organization.setOrganizationName(reqOrganizationAddDTO.getOrganizationName());
			organization.setOrganizationAddr(reqOrganizationAddDTO.getOrganizationAddr());
			organization.setBusinessLicence(reqOrganizationAddDTO.getBusinessLicence());
			organization.setContacts(reqOrganizationAddDTO.getContacts());
			organization.setContactsNumber(reqOrganizationAddDTO.getContactsNumber());
			organization.setContactsEmail(reqOrganizationAddDTO.getContactsEmail());
			try {
				if (ToolUtil.isNotEmpty(reqOrganizationAddDTO.getLicenseStartDate())) {
					organization.setLicenseStartDate(sdf.parse(reqOrganizationAddDTO.getLicenseStartDate()));
				}
				if (ToolUtil.isNotEmpty(reqOrganizationAddDTO.getLicenseEndDate())) {
					organization.setLicenseEndDate(sdf.parse(reqOrganizationAddDTO.getLicenseEndDate()));
				}
			} catch (ParseException e) {
				e.printStackTrace();
				throw new BussinessException(BizExceptionEnum.SERVER_ERROR);
			}
			organization.setOrganizationType(reqOrganizationAddDTO.getOrganizationType());
			organization.setOrganizationStatus(reqOrganizationAddDTO.getOrganizationStatus());
			organization.setRemarks(reqOrganizationAddDTO.getRemarks());
			organization.setCreateUserId(currentId);
			organization.setCreateTime(new Date());
			organizationDao.addOrganization(organization);

			// 添加机构和城市管理关系
			CityRefOrganization cityRefOrganization = new CityRefOrganization();
			cityRefOrganization.setOrganizationId(organization.getOrganizationId());
			cityRefOrganization.setCityId(reqOrganizationAddDTO.getCityId());
			organizationDao.addCityRefOrganization(cityRefOrganization);
		}
	}

	/**
	 * @Description: 修改机构
	 * @date 2016年12月7日 下午9:58:12
	 * @author SUNZHICHENG
	 * @since V2.6.2
	 */
	@LogRecord(moduleName="公司管理",option="修改")
	@Override
	@Transactional(readOnly = false)
	public void updateOrganization(ReqOrganizationAddDTO reqOrganizationAddDTO) {
		// 获取要修改的机构信息
		Organization organizationInfo = organizationDao.getOrganizationInfo(reqOrganizationAddDTO.getOrganizationId());

		// 获取当前登录用户信息
		ShiroUser shiroUser = ShiroKit.getUser();
		Integer currentId = shiroUser.getId();

		if (ToolUtil.isNotEmpty(reqOrganizationAddDTO.getOrganizationName())) {
			// 获取是否存在此机构
			List<Organization> organizationList = organizationDao
					.getOrganizationByName(reqOrganizationAddDTO.getOrganizationName());

			if (organizationList.size() > 0) {
				for (Organization organization : organizationList) {
					// 判断已存在信息与要修改的数据是否同一信息
					if (!organization.getOrganizationId().equals(organizationInfo.getOrganizationId())) {
						throw new BussinessException(BizExceptionEnum.INFO_REPEAT);
					}
				}
			}

			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

			// 添加机构信息
			Organization organization = organizationInfo;
			organization.setOrganizationId(reqOrganizationAddDTO.getOrganizationId());
			// 公司类型为0总公司，设置其父级id为0
			if (reqOrganizationAddDTO.getOrganizationType() == 0) {
				organization.setParentId(0);
				organization.setParentIds("0,");
			} else {
				organization.setParentId(reqOrganizationAddDTO.getParentId());
				organization.setParentIds(reqOrganizationAddDTO.getParentId() + ",");
			}

			organization.setCityId(reqOrganizationAddDTO.getCityId());
			organization.setCityName(reqOrganizationAddDTO.getCityName());
			organization.setOrganizationName(reqOrganizationAddDTO.getOrganizationName());
			organization.setOrganizationAddr(reqOrganizationAddDTO.getOrganizationAddr());
			organization.setBusinessLicence(reqOrganizationAddDTO.getBusinessLicence());
			organization.setContacts(reqOrganizationAddDTO.getContacts());
			organization.setContactsNumber(reqOrganizationAddDTO.getContactsNumber());
			organization.setContactsEmail(reqOrganizationAddDTO.getContactsEmail());
			try {
				if (ToolUtil.isNotEmpty(reqOrganizationAddDTO.getLicenseStartDate())) {
					organization.setLicenseStartDate(sdf.parse(reqOrganizationAddDTO.getLicenseStartDate()));
				}
				if (ToolUtil.isNotEmpty(reqOrganizationAddDTO.getLicenseEndDate())) {
					organization.setLicenseEndDate(sdf.parse(reqOrganizationAddDTO.getLicenseEndDate()));
				}
			} catch (ParseException e) {
				e.printStackTrace();
				throw new BussinessException(BizExceptionEnum.SERVER_ERROR);
			}
			organization.setOrganizationType(reqOrganizationAddDTO.getOrganizationType());
			organization.setOrganizationStatus(reqOrganizationAddDTO.getOrganizationStatus());
			organization.setRemarks(reqOrganizationAddDTO.getRemarks());
			organization.setCreateUserId(organizationInfo.getCreateUserId());
			organization.setCreateTime(organizationInfo.getCreateTime());
			organization.setUpdateUserId(currentId);
			organization.setUpdateTime(new Date());
			organizationDao.addOrganization(organization);

			// 根据机构id获取机构和城市关联
			CityRefOrganization cityRefOrganization = organizationDao
					.getCityRefOrganization(reqOrganizationAddDTO.getOrganizationId());
			// 修改城市机构关联关系
			cityRefOrganization.setCityId(reqOrganizationAddDTO.getCityId());
			organizationDao.addCityRefOrganization(cityRefOrganization);

		}

	}

	/**
	 * @Description: 根据公司类型获取公司列表
	 * @param organizationType
	 * @date 2016年12月6日 上午11:32:47
	 * @author SUNZHICHENG
	 * @since V2.6.2
	 */
	@Override
	@Transactional(readOnly = true)
	public List<Organization> getOrganizationListByType(Integer organizationType) {
		return organizationDao.getOrganizationListByType(organizationType);
	}

	/**
	 * @Description:获取公司列表（或组合查询）
	 * @date 2016年12月6日 下午8:02:57
	 * @author SUNZHICHENG
	 * @since V2.6.2
	 */
	@Transactional(readOnly = true)
	@Override
	public Page<ResOrganizationDTO> getOrganizationList(ReqOrganizationListDTO reqOrganizationListDTO, Integer start,
			Integer length) {
		// 获取机构分页对象
		Page<ResOrganizationDTO> organizationList = organizationDao.getOrganizationList(reqOrganizationListDTO, start,
				length);

		if (ToolUtil.isNotEmpty(organizationList)) {
			// 获取机构列表数据
			List<ResOrganizationDTO> list = organizationList.getList();
			if (list.size() > 0) {
				for (ResOrganizationDTO resOrganizationDTO : list) {
					if (ToolUtil.isNotEmpty(resOrganizationDTO.getParentId())) {
						// 根据当前机构的父级id查询父级机构名称
						Organization organization = Db.findById(resOrganizationDTO.getParentId(), Organization.class);
						if (ToolUtil.isNotEmpty(organization)) {
							// 添加父级机构名称到机构列表中
							resOrganizationDTO.setParentOrganizationName(organization.getOrganizationName());
						}
					}
				}
			}
		}
		return organizationList;
	}

	/**
	 * @Description: 根据省份、城市获取机构
	 * @date 2016年12月7日 下午8:17:47
	 * @author SUNZHICHENG
	 * @since V2.6.2
	 */
	@Override
	@Transactional(readOnly = true)
	public List<ResOrganizationDTO> getOrganization(Integer proviceId, Integer sysCityId) {
		return organizationDao.getOrganization(proviceId, sysCityId);
	}

	/**
	 * 
	 * @Title: getOrganizationByDriverId @Description: 根据用户id查询用户的机构 @param
	 * userId @param @return 参数说明 @return Organization 返回类型 @throws
	 */
	@Override
	@Transactional(readOnly = true)
	public Organization getOrganizationByUserId(Integer userId) {

		if (userId == null) {
			return null;
		}
		return organizationDao.getOrganizationByUserId(userId);
	}

	/**
	 * @Description: 根据省份、城市获取机构
	 * @date 2016年12月7日 下午8:17:47
	 * @author hufan
	 * @since V2.6.2
	 */
	@Override
	@Transactional(readOnly = true)
	public List<Integer> getOrganizationIds(Integer proviceId, Integer sysCityId) {

		return organizationDao.getOrganizationIds(proviceId, sysCityId);
	}

}
